using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using MapInfo.Toolbox.Core;
using MapInfo.Toolbox.UI.ViewModels;
using System.ComponentModel.Composition;

namespace MapInfo.Toolbox.UI.Services
{
    /// <summary>
    /// Loads MEF exports from dlls in the MapInfo.Toolbox\Modules folder.
    /// </summary>
    public class MEFModuleLoader : IModuleLoader
    {
        /// <summary>
        /// Scans the module directory a loads all the modules into the application.
        /// </summary>
        public void LoadModules()
        {
            //search the widget directory and also the current assembly for Widgets
            AggregateCatalog _catalog = new AggregateCatalog(
                            new DirectoryCatalog(ModuleDirectory.FullName, "*.dll"),
                            new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            CompositionContainer _container = new CompositionContainer(_catalog);
            _container.ComposeParts(this);
        }

        [ImportMany(typeof(IToolboxModule))]
        public Lazy<IToolboxModule>[] Modules { get; set; }

        private  DirectoryInfo ModuleDirectory
        {
            get
            {
                return new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules"));
            }
        }
    }
}